package com.taptech.doufu.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.telephony.TelephonyManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.taptech.doufu.sdk.universalimageloader.core.ImageLoader;
import com.taptech.doufu.ui.activity.NovelSectionDetailsActivity;
import com.taptech.doufu.app.WeMediaApplication;
import com.taptech.doufu.bean.BaseBean;
import com.taptech.doufu.bean.HomeTopBean;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.net.httputils.HttpResponseObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * <p>
 * Company: DiaoBao
 * </p>
 *
 * @author huangzh
 * @date 2014-3-20
 */
public class DiaobaoUtil
{

    private static String IMEI;


    public static int getIntFromJons(String key, JSONObject json)
    {
        try
        {
            String value = json.getString(key);
            if (isInteger(value))
            {
                return Integer.parseInt(value);
            }
        } catch (JSONException e)
        {
            e.printStackTrace();
        }

        return -1;
    }
    public static boolean isInteger(String str)
    {
        return str.matches("[\\d]+");
    }

    public static int String2Int(String s)
    {
        try
        {
            return Integer.parseInt(s);
        } catch (Exception e)
        {
            TTLog.s(e.getMessage());
        }
        return 0;
    }

    public static String String2NumString(String s)
    {
        try
        {
            return "" + Integer.parseInt(s);
        } catch (Exception e)
        {
            TTLog.s(e.getMessage());
        }
        return "0";
    }


    /**
     * 把一个json对象数组转换成，bean数组
     *
     * @param beanClass
     * @param array
     * @return
     */
    public static <T extends BaseBean> List<T> json2list(Class<T> beanClass, JSONArray array)
    {
        Log.v("jsonArray2BeanList2", "enter");
        List<T> datas = new ArrayList<T>(array.length());
        T data;
        try
        {
            for (int i = 0; i < array.length(); i++)
            {
                if (array.getJSONObject(i) == null)
                    continue;
                data = beanClass.newInstance();
                data.setJson2(array.getJSONObject(i));
                datas.add(data);
            }
        } catch (InstantiationException e)
        {
            e.printStackTrace();
        } catch (IllegalAccessException e)
        {
            e.printStackTrace();
        } catch (JSONException e)
        {
            e.printStackTrace();
        }
        return datas;
    }

    /**
     * @param beanClass
     * @param array
     * @return
     * @deprecated use array2list
     */
    public static LinkedList jsonArray2BeanList(Class beanClass, JSONArray array)
    {
        LinkedList<Object> datas = new LinkedList<Object>();
        BaseBean data;
        try
        {
            for (int i = 0; i < array.length(); i++)
            {
                if (array.getJSONObject(i) == null)
                    continue;
                data = (BaseBean) beanClass.newInstance();
                data.setJson(array.getJSONObject(i));
                datas.add(data);
            }
        } catch (InstantiationException e)
        {
            e.printStackTrace();
        } catch (IllegalAccessException e)
        {
            e.printStackTrace();
        } catch (JSONException e)
        {
            e.printStackTrace();
        }
        return datas;
    }

    public static String getIMEI()
    {
        return "";
    }

    public static boolean isMobileNO(String mobiles)
    {
        Pattern p = Pattern.compile("^((1[0-9][0-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    public static boolean isEmail(String email)
    {
        if (email == null)
        {
            return false;
        }

        String regular = "^([\\w\\-\\.]+)@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        Pattern pattern = Pattern.compile(regular);

        Matcher matcher = pattern.matcher(email);

        if (!matcher.find())
        {
            return false;
        }
        return true;
    }

    public static String getStringFromJSONObject(JSONObject json, String key)
    {
        try
        {
            if (json.has(key))
            {
                return json.getString(key);
            }
        } catch (JSONException e)
        {
            e.printStackTrace();
        }
        return "";
    }

    public static int getIntFromJSONObject(JSONObject json, String key)
    {
        try
        {
            if (json.has(key))
            {
                return json.getInt(key);
            }
        } catch (JSONException e)
        {
            e.printStackTrace();
        }
        return 0;
    }

    public static File getLastModifyFile(File files[])
    {
        File temp = null;
        for (int i = 0; i < files.length; i++)
        {
            if (temp == null)
            {
                temp = files[i];
                continue;
            }
            if (temp != null && temp.lastModified() < files[i].lastModified())
                temp = files[i];

        }
        return temp;
    }
    public static String seconds2TimeString(long seconds)
    {
        String timeString = "";
        long space = System.currentTimeMillis() / 1000 - seconds;
        if (space < 60)
        {
            timeString = "刚刚";
        } else if (space < 60 * 60)
        {
            timeString = space / 60 + "分钟前";
        } else if (space < 60 * 60 * 24)
        {
            timeString = space / (60 * 60) + "小时前";
        } else if (space < 60 * 60 * 24 * 30)
        {
            timeString = space / (60 * 60 * 24) + "天前";
        } else if (space < 60 * 60 * 24 * 30 * 12)
        {
            timeString = space / (60 * 60 * 24 * 30) + "个月前";
        } else
        {
            timeString = space / (60 * 60 * 24 * 30 * 12) + "年前";
        }
        return timeString;
    }

    public static String seconds2TimeStringLater(long seconds)
    {
        String timeString = "";
        long space = seconds - System.currentTimeMillis() / 1000;
        if (space < 60)
        {
            timeString = "已过期";
        } else if (space < 60 * 60)
        {
            timeString = space / 60 + "分钟后";
        } else if (space < 60 * 60 * 24)
        {
            timeString = space / (60 * 60) + "小时后";
        } else if (space < 60 * 60 * 24 * 30)
        {
            timeString = space / (60 * 60 * 24) + "天后";
        } else if (space < 60 * 60 * 24 * 30 * 12)
        {
            timeString = space / (60 * 60 * 24 * 30) + "个月后";
        } else
        {
            timeString = space / (60 * 60 * 24 * 30 * 12) + "年后";
        }
        return timeString;
    }

    public static long Date2seconds(String time){
        String reTime = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date;
        try {
            date = sdf.parse(time);
            long l = date.getTime();
            String str = String.valueOf(l);
            reTime = str.substring(0, 10);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return Long.valueOf(reTime);
    }



    public static FileType getFileType(String filePath)
    {

        String fileHead;
        try
        {
            fileHead = getFileContent(filePath);
            if (fileHead == null || fileHead.length() == 0)
            {
                return null;
            }
            fileHead = fileHead.toUpperCase();
            FileType[] fileTypes = FileType.values();

            for (FileType type : fileTypes)
            {
                if (fileHead.startsWith(type.getValue()))
                {
                    return type;
                }
            }
        } catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    private static String getFileContent(String filePath) throws IOException
    {

        byte[] b = new byte[28];

        InputStream inputStream = null;

        try
        {
            inputStream = new FileInputStream(filePath);
            inputStream.read(b, 0, 28);
        } catch (IOException e)
        {
            e.printStackTrace();
            throw e;
        } finally
        {
            if (inputStream != null)
            {
                try
                {
                    inputStream.close();
                } catch (IOException e)
                {
                    e.printStackTrace();
                    throw e;
                }
            }
        }
        return bytesToHexString(b);
    }

    private static String bytesToHexString(byte[] src)
    {

        StringBuilder stringBuilder = new StringBuilder();
        if (src == null || src.length <= 0)
        {
            return null;
        }
        for (int i = 0; i < src.length; i++)
        {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2)
            {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }


    public static int getUTFStirngLength(String value)
    {
        int valueLength = 0;
        String chinese = "[\u0391-\uFFE5]";
        /* 获取字段值的长度，如果含中文字符，则每个中文字符长度为2，否则为1 */
        for (int i = 0; i < value.length(); i++)
        {
            /* 获取一个字符 */
            String temp = value.substring(i, i + 1);
            /* 判断是否为中文字符 */
            if (temp.matches(chinese))
            {
                /* 中文字符长度为2 */
                valueLength += 2;
            } else
            {
                /* 其他字符长度为1 */
                valueLength += 1;
            }
        }
        return valueLength;
    }

    public enum FileType
    {

        /**
         * JEPG.
         */
        JPEG("FFD8FF"),

        /**
         * PNG.
         */
        PNG("89504E47"),

        /**
         * GIF.
         */
        GIF("47494638"),

        /**
         * TIFF.
         */
        TIFF("49492A00"),

        /**
         * Windows Bitmap.
         */
        BMP("424D"),

        /**
         * CAD.
         */
        DWG("41433130"),

        /**
         * Adobe Photoshop.
         */
        PSD("38425053"),

        /**
         * Rich Text Format.
         */
        RTF("7B5C727466"),

        /**
         * XML.
         */
        XML("3C3F786D6C"),

        /**
         * HTML.
         */
        HTML("68746D6C3E"),

        /**
         * Email [thorough only].
         */
        EML("44656C69766572792D646174653A"),

        /**
         * Outlook Express.
         */
        DBX("CFAD12FEC5FD746F"),

        /**
         * Outlook (pst).
         */
        PST("2142444E"),

        /**
         * MS Word/Excel.
         */
        XLS_DOC("D0CF11E0"),

        /**
         * MS Access.
         */
        MDB("5374616E64617264204A"),

        /**
         * WordPerfect.
         */
        WPD("FF575043"),

        /**
         * Postscript.
         */
        EPS("252150532D41646F6265"),

        /**
         * Adobe Acrobat.
         */
        PDF("255044462D312E"),

        /**
         * Quicken.
         */
        QDF("AC9EBD8F"),

        /**
         * Windows Password.
         */
        PWL("E3828596"),

        /**
         * ZIP Archive.
         */
        ZIP("504B0304"),

        /**
         * RAR Archive.
         */
        RAR("52617221"),

        /**
         * Wave.
         */
        WAV("57415645"),

        /**
         * AVI.
         */
        AVI("41564920"),

        /**
         * Real Audio.
         */
        RAM("2E7261FD"),

        /**
         * Real Media.
         */
        RM("2E524D46"),

        /**
         * MPEG (mpg).
         */
        MPG("000001BA"),

        /**
         * Quicktime.
         */
        MOV("6D6F6F76"),

        /**
         * Windows Media.
         */
        ASF("3026B2758E66CF11"),

        /**
         * MIDI.
         */
        MID("4D546864");

        private String value = "";

        /**
         * Constructor.
         *
         * @param
         */
        private FileType(String value)
        {
            this.value = value;
        }

        public String getValue()
        {
            return value;
        }

        public void setValue(String value)
        {
            this.value = value;
        }
    }

    public static void allListScroll(int scrollState)
    {
        switch (scrollState)
        {
            case OnScrollListener.SCROLL_STATE_IDLE:
                ImageLoader.getInstance().resume();
                break;
            case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
                ImageLoader.getInstance().pause();
                break;
            case OnScrollListener.SCROLL_STATE_FLING:
                ImageLoader.getInstance().pause();
                break;
        }
    }

    public static String getErrorTips(HttpResponseObject res)
    {
        String tips = "操作失败";
        if (res.getStatus() == Constant.STATUS_TIME_OUT)
            tips = Constant.loadingFail;
        else if (!TextUtils.isEmpty(res.getUser_msg()))
            tips = res.getUser_msg();
        return tips;
    }

    public static void contentClick(Context context, HomeTopBean topBean)
    {

        if (topBean == null)
        {
            return;
        }
        int objectType = DiaobaoUtil.String2Int(topBean.getObject_type());
        // int targetType = DiaobaoUtil.String2Int(topBean.getTagType());
        int topicType = DiaobaoUtil.String2Int(topBean.getTopic_type());

        if (objectType == Constant.CONTENT_TYPE_TOPIC)
        {// 专题 5
            if (topicType == Constant.OBJECT_TYPE_NOVEL)
            {
                StartActivityUtil.novelOnclick(context, topBean.getId());
            }
        }else if (objectType == Constant.CONTENT_TYPE_WORDS)
        {
            Intent intent = new Intent(context, NovelSectionDetailsActivity.class);
            intent.putExtra(Constant.ARTICLE_ID, topBean.getId());
            intent.putExtra(Constant.ARTICLE_NOVELID, topBean.getTopicId());
            context.startActivity(intent);

        }

    }



    /**
     * 高亮显示文字
     */
    public static SpannableString textLighterColor(String content, String matcherText)
    {
        SpannableString textSpan = null;


        try
        {
            textSpan = new SpannableString(content);
            Pattern p = Pattern.compile(matcherText, Pattern.CASE_INSENSITIVE);
            Matcher m = p.matcher(content);
            while (m.find())
            {
                ForegroundColorSpan span = new ForegroundColorSpan(Color.parseColor("#ff6e70"));
                int start = m.start();
                int end = m.end();
                textSpan.setSpan(span, start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            }
        } catch (PatternSyntaxException e)
        {
            // TODO: handle exception
            e.printStackTrace();
        }
        return textSpan;
    }

    // 隐藏软键盘
    public static void hideInputManager(Context ct)
    {
        try
        {
            ((InputMethodManager) ct.getSystemService(ct.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(((Activity) ct).getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }


    /**
     * 广播插入图片
     *
     * @param mContext
     * @param path
     */
    public static void insertPhoto(Context mContext, String path)
    {
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(new File(path));
        intent.setData(uri);
        mContext.sendBroadcast(intent);
    }

    /***
     * 获取网络数据是否成功
     *
     * @param response
     * @return
     */
    public static boolean getDataSuccess(HttpResponseObject response, Context mContext)
    {
        boolean flag = false;
        if (response.getStatus() == 0 && response.getFail_code() == 0)
        {
            flag = true;
        } else
        {
            flag = false;
            UIUtil.toastMessage(mContext, DiaobaoUtil.getErrorTips(response));
        }
        return flag;
    }

    /**
     * 献花成功提示语
     */
    public static void flowerFinish(TextView flowerFinishTips, int flowerFinishCount, String object)
    {
        String finishFlower = "";
        if (flowerFinishCount < 20)
        {
            finishFlower = "送花" + flowerFinishCount + "朵，消耗5个豆子";
        } else if (flowerFinishCount <= 29)
        {
            finishFlower = "送花" + flowerFinishCount + "朵，消耗5个豆子";
        } else if (flowerFinishCount <= 39)
        {
            finishFlower = "送花" + flowerFinishCount + "朵，消耗5个豆子";
        } else if (flowerFinishCount <= 49)
        {
            finishFlower = "送花" + flowerFinishCount + "朵，消耗5个豆子";
        } else if (flowerFinishCount <= 59)
        {
            finishFlower = "送花" + flowerFinishCount + "朵，消耗5个豆子";
        } else
        {
            finishFlower = "送花" + flowerFinishCount + "朵，消耗5个豆子";
        }
        SpannableStringBuilder spannable = new SpannableStringBuilder(finishFlower);
        ForegroundColorSpan span = new ForegroundColorSpan(Color.parseColor("#ff6e70"));
        spannable.setSpan(span, 2, 2 + String.valueOf(flowerFinishCount).length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        flowerFinishTips.setText(spannable);
    }

    /**
     * 献花成功提示语
     */
    public static void flowerFinishCP(TextView flowerFinishTips, int flowerFinishCount, String object)
    {
        String finishFlower = "";
        if (flowerFinishCount < 20)
        {
            finishFlower = "送花" + flowerFinishCount + "朵，消耗5个豆子！";
        } else if (flowerFinishCount <= 29)
        {
            finishFlower = "送花" + flowerFinishCount + "朵，消耗5个豆子!";
        } else if (flowerFinishCount <= 39)
        {
            finishFlower = "送花" + flowerFinishCount + "朵，消耗5个豆子!";
        } else if (flowerFinishCount <= 49)
        {
            finishFlower = "送花" + flowerFinishCount + "朵，消耗5个豆子!";
        } else if (flowerFinishCount <= 59)
        {
            finishFlower = "送花" + flowerFinishCount + "朵，消耗5个豆子!";
        } else
        {
            finishFlower = "送花" + flowerFinishCount + "朵，消耗5个豆子!";
        }
        SpannableStringBuilder spannable = new SpannableStringBuilder(finishFlower);
        ForegroundColorSpan span = new ForegroundColorSpan(Color.parseColor("#ff6e70"));
        spannable.setSpan(span, 2, 2 + String.valueOf(flowerFinishCount).length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        flowerFinishTips.setText(spannable);
    }

    /***
     * 加载勋章图片
     *
     * @param imgUrl
     * @param medalImg
     */
    public static void setMedalImgView(String imgUrl, ImageView medalImg)
    {
        if (imgUrl != null && imgUrl.length() > 5)
        {
            GlideUtil.displayCircleImage(medalImg, imgUrl);
            medalImg.setVisibility(View.VISIBLE);
        } else
        {
            medalImg.setVisibility(View.GONE);
        }
    }

    /***
     * 小说完成状态（连载或完结）
     */
    public static void novelFinish(TextView novelText, String isFinished) {
        if ("1".equalsIgnoreCase(isFinished)) {
            novelText.setText("已完结");
            if (WeMediaApplication.getInstance().isDayNightMode_Night) {
                novelText.setTextColor(Color.parseColor("#557270"));
            } else {
                novelText.setTextColor(Color.parseColor("#88c2bd"));
            }
        } else {
            novelText.setText("连载中");
            if (WeMediaApplication.getInstance().isDayNightMode_Night) {
                novelText.setTextColor(Color.parseColor("#905d60"));
            } else {
                novelText.setTextColor(Color.parseColor("#ff979e"));
            }
        }
    }
    public static boolean isRequestResult(HttpResponseObject response)
    {
        return response.getStatus() == 0 && response.getFail_code() == 0;
    }

    /**
     * 去除空格检测字符串长度
     */
    public static int getStringSizeNoSpace(String t)
    {
        if (t == null)
        {
            return 0;
        }
        Pattern p = Pattern.compile("\\s+");
        String temp = p.matcher(t).replaceAll("");
        return temp.length();
    }

    public static int getStringSizeNoNull(String t)
    {
        if (t == null)
        {
            return 0;
        }
//        String temp = t.replaceAll("[^0-9a-zA-Z\\u4e00-\\u9fa5.，,。;；:：?？!！、@<>《》'‘’“”\"]+","");
        String temp = t.replaceAll("[^0-9a-zA-Z\\u4e00-\\u9fa5.﹒·，,。;；﹔︰:﹕：…‥﹖?？!！﹗﹏、﹑～→—/–@*#￥%&︿§￥<>〈〉《》｛｝﹛﹜﹙﹚()+\\-（）'’‘’“”‵′\"〝〞‖【】\\[\\]〖〗『』〔〕﹝﹞]+","");
        return temp.length();
    }



    /**
     * 判断一个图片的url是不是gif
     *
     * @param urlStr
     * @return
     */
    public static boolean isImageUrlGif(String urlStr)
    {
        boolean isGifType = false;
        try
        {
            URL url = new URL(urlStr);
            String urlPath = url.getPath();
            if (urlPath != null)
            {
                int strStart = urlPath.indexOf(".");
                if (strStart > 0)
                {
                    String pathType = urlPath.substring(strStart);
                    if (pathType.equals(".gif"))
                    {
                        isGifType = true;
                    }

                }
            }
        } catch (MalformedURLException e)
        {
            e.printStackTrace();
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return isGifType;
    }

    public static String getStringNoSpace(String str)
    {
        String string = str;
        string.replaceAll("\\s+", "");
        return string;
    }
}
